﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace EcoSystem
{
    public class EnterpriseAppService : CrudAppService<
        Enterprise,
        EnterpriseDto,
        Guid,
        GetEnterpriseInput,
        CreateOrUpdateEnterpriseDto,
        CreateOrUpdateEnterpriseDto>, IEnterpriseAppService
    {
        public EnterpriseAppService(IRepository<Enterprise, Guid> repository) : base(repository)
        {
        }

        public override async Task<PagedResultDto<EnterpriseDto>> GetListAsync(GetEnterpriseInput input)
        {
            var query = (await Repository.GetQueryableAsync()).AsNoTracking()
                .WhereIf(!input.Name.IsNullOrWhiteSpace(), x => x.Name.Contains(input.Name) || x.Code.StartsWith(input.Name) || x.BusinessCode.StartsWith(input.Name))
                .WhereIf(!input.Code.IsNullOrWhiteSpace(), x => x.Code.StartsWith(input.Code))
                .WhereIf(!input.Type.IsNullOrWhiteSpace(), x => x.Type.StartsWith(input.Type))
                .WhereIf(input.Status.HasValue, x => x.Status == input.Status);
            var total = await query.CountAsync();
            var items = await query.OrderByDescending(x => x.Id).PageBy(input).ToListAsync();
            return new PagedResultDto<EnterpriseDto>()
            {
                Items = await MapToGetListOutputDtosAsync(items),
                TotalCount = total
            };
        }

        public async Task<List<EnterpriseDto>> GetAllListAsync(GetEnterpriseInput input)
        {
            var query = (await Repository.GetQueryableAsync()).AsNoTracking()
                .WhereIf(!input.Name.IsNullOrWhiteSpace(), x => x.Name.Contains(input.Name) || x.Code.StartsWith(input.Name) || x.BusinessCode.StartsWith(input.Name))
                .WhereIf(!input.Code.IsNullOrWhiteSpace(), x => x.Code.StartsWith(input.Code))
                .WhereIf(!input.Type.IsNullOrWhiteSpace(), x => x.Type.StartsWith(input.Type))
                .WhereIf(input.Status.HasValue, x => x.Status == input.Status);
            var items = await query.OrderByDescending(x => x.Id).ToListAsync();
            return await MapToGetListOutputDtosAsync(items);
        }
    }
}
